package com.useeinfo.oa.open.api.repairOrder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.framework.sugar.tools.qiniu.UploadFactory;
import com.useeinfo.framework.sugar.tools.qiniu.UploadUtil;
import com.useeinfo.oa.common.enums.ResultEnums;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.AreaBiz;
import com.useeinfo.oa.modules.base.biz.DictInfoBiz;
import com.useeinfo.oa.modules.base.biz.FacilityCatBiz;
import com.useeinfo.oa.modules.base.entity.DictInfo;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.repair.biz.RepairLevelBiz;
import com.useeinfo.oa.modules.repair.biz.RepairOrderBiz;
import com.useeinfo.oa.modules.repair.biz.RepairWorkLogBiz;
import com.useeinfo.oa.modules.repair.biz.TroubleCatBiz;
import com.useeinfo.oa.modules.repair.entity.RepairLevel;
import com.useeinfo.oa.modules.repair.entity.RepairOrder;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Auther: xudong.sun
 * @Date: 2018/12/14 09:57
 * @Description:维修管理接口
 */
@Controller
@RequestMapping("/api/repairOrder")
public class RepairOrderAPI {

    @Autowired
    private RepairOrderBiz repairOrderBiz;

    @Autowired
    private TroubleCatBiz troubleCatBiz;

    @Autowired
    private RepairWorkLogBiz repairWorkLogBiz;

    @Autowired
    private RepairLevelBiz repairLevelBiz;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private DictInfoBiz dictInfoBiz;

    /**
     * 维修单详情
     */
    @RequestMapping("/repairOrderDetail")
    @ResponseBody
    public ResultDto repairOrderDetail(String repairOrderId) {
        return repairOrderBiz.repairOrderDetail(repairOrderId);
    }

    /**
     * 维修单列表接口
     * 1:待接单
     * 2:未完成
     * 3:审批中
     * 4:已结束
     */
    /**
     *
     * @param pageIndex
     * @param pageSize
     * @param status 工单状态
     * @param searchParam 查询参数
     * @param date 日期
     * @param startDate
     * @param endDate
     * @param catId 专业
     * @param areaId  区域
     * @param levelId 紧急
     * @param typeId 保修类型
     * @param repairPosition 地址
     * @param receiveUser 接单人
     * @return
     */
    @RequestMapping("/repairOrderList")
    @ResponseBody
    public ResultDto repairOrderList(String pageIndex, String pageSize, String status, String searchParam, String date, String startDate, String endDate,String catId,String areaId,String levelId,String typeId,String repairPosition,String receiveUser) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (null == systemUser) {
            return ResultUtil.error(ResultEnums.NO_LOGIN_MESSAGE);
        }
        if (null == enterprise) {
            return ResultUtil.error("企业信息有误");
        }
        return repairOrderBiz.getRepairOrders(pageIndex, pageSize, status, searchParam, systemUser, enterprise, date,startDate,endDate,catId,areaId,levelId,typeId,repairPosition,receiveUser);
    }

    /**
     * 接单接口
     */
    @RequestMapping("/taking")
    @ResponseBody
    public ResultDto taking(String repairOrderId) {
        return repairOrderBiz.taking(repairOrderId);
    }

    /**
     * 到场
     */
    @RequestMapping("/presence")
    @ResponseBody
    public ResultDto presence(String presencePhotos, String repairOrderId, String longitude, String latitude) {
        return repairOrderBiz.presence(presencePhotos, repairOrderId, longitude, latitude);
    }


    /**
     * 上传接口
     */
    @RequestMapping("/upload")
    @ResponseBody
    public ResultDto upload(MultipartFile file, String type) {
        return repairOrderBiz.upload(file, type);
    }

    /**
     * 创建维修单接口
     */
    @RequestMapping("/addRepair")
    @ResponseBody
    public ResultDto addRepair(String assignUser, String assignPosition, String code, String reportContent, String reportAddress, String reportLevelId, String reportMajorId, String photos, String recordingId, String type, String areaId, String facilityPosition) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        return repairOrderBiz.addRepair(assignUser, assignPosition, code, reportContent, reportAddress, reportLevelId, reportMajorId, photos, recordingId, type, areaId, facilityPosition, systemUser, enterprise, null);
    }


    /**
     * 添加参与人
     */
    @RequestMapping("/addPartner")
    @ResponseBody
    public ResultDto addPartner(String repairOrderId, String partnerArray) {
        return repairOrderBiz.addPartner(repairOrderId, partnerArray);
    }

    /**
     * 移除参与人
     */
    @RequestMapping("/removePartner")
    @ResponseBody
    public ResultDto removePartner(String id) {
        return repairOrderBiz.removePartner(id);
    }

    /**
     * 字典下拉选接口
     */
    @RequestMapping("/getDictSelect")
    @ResponseBody
    public ResultDto getDictSelect(String typeCode) {
        return repairOrderBiz.getDictSelect(typeCode);
    }


    /**
     * 确认故障
     */
    @RequestMapping("/confirmFault")
    @ResponseBody
    public ResultDto confirmFault(String repairOrderId, String troubleCatId, String faultReason, Boolean inRepairScope) {
        return repairOrderBiz.confirmFault(repairOrderId, troubleCatId, faultReason, inRepairScope);
    }

    /**
     * 维修-确认完成
     */
    @RequestMapping("/repairConfirm")
    @ResponseBody
    public ResultDto repairConfirm(String repairOrderId, String participantInputs, String spareParts, String finishPhoto, String unrepairReason, String measure, String repairFinishTime, String faultReason, Boolean inRepairScope, String troubleCatId) {
        RepairOrder repairOrder = repairOrderBiz.findModel(StringConverters.ToLong(repairOrderId));
        JSONArray jsonArray = JSON.parseArray(participantInputs);
        return repairOrderBiz.repairConfirm(repairOrder, jsonArray, spareParts, finishPhoto, unrepairReason, measure, repairFinishTime, faultReason, inRepairScope, troubleCatId);
    }

    /**
     * 临时保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public ResultDto save(String repairOrderId, String spareParts, String finishPhotos, String unrepairReason, String measure, String faultReason, Boolean inRepairScope, String troubleCatId, String workingHours) {
        return repairOrderBiz.save(repairOrderId, spareParts, finishPhotos, unrepairReason, measure, faultReason, inRepairScope, troubleCatId, workingHours);
    }


    /**
     * 转单
     */
    @RequestMapping("/transfer")
    @ResponseBody
    public ResultDto transfer(String repairOrderId, String userIds) {
        return repairOrderBiz.transfer(repairOrderId, userIds);
    }

    /**
     * 转单列表
     */
    @RequestMapping("/transferList")
    @ResponseBody
    public ResultDto transferList(String searchParam, String pageIndex, String pageSize) {
        return repairOrderBiz.transferList(searchParam, pageIndex, pageSize);
    }

    /**
     * 关注
     */
    @RequestMapping("/focus")
    @ResponseBody
    public ResultDto focus(String repairOrderId, Boolean type) {
        return repairOrderBiz.focus(repairOrderId, type);
    }

    /**
     * 审核
     */
    @RequestMapping("/audit")
    @ResponseBody
    public ResultDto audit(String repairOrderId, Boolean type, String remark) {
        return repairOrderBiz.audit(repairOrderId, type, remark);
    }

    @RequestMapping("/finalAudit")
    @ResponseBody
    public ResultDto finalAudit(String repairOrderId, String score, String remark) {
        return repairOrderBiz.finalAudit(repairOrderId, remark, score);
    }


    /**
     * 添加/修改工作日志
     */
    @RequestMapping("/addLog")
    @ResponseBody
    public ResultDto addLog(String logId, String workLogCatId, String workLogLevelId, String workContent, String photos, String repairOrderId) {
        return repairWorkLogBiz.addLog(logId, workLogCatId, workLogLevelId, workContent, photos, repairOrderId);
    }

    /**
     * 工作日志列表
     */
    @RequestMapping("/repairWorkLogList")
    @ResponseBody
    public ResultDto repairWorkLogList(String pageIndex, String pageSize, String id) {
        return repairWorkLogBiz.repairWorkLogList(pageIndex, pageSize, id);
    }

    /**
     * 工作日志详情
     */
    @RequestMapping("/repairWorkLogDetail")
    @ResponseBody
    public ResultDto repairWorkLogDetail(String id) {
        return repairWorkLogBiz.repairWorkLogDetail(id);
    }

    /**
     * 紧急程度
     */
    @RequestMapping("/repairLevel")
    @ResponseBody
    public ResultDto repairLevel() {
        return repairLevelBiz.repairLevel();
    }

    /**
     * 维修历史纪录
     */
    @RequestMapping("/repairHistory")
    @ResponseBody
    public ResultDto repairHistory(String facilityId, String pageIndex, String pageSize) {
        return repairOrderBiz.repairHistory(facilityId, pageIndex, pageSize);
    }

    @RequestMapping("/process")
    @ResponseBody
    public ResultDto process(String repairOrderId) {
        return repairOrderBiz.process(repairOrderId);
    }

    /**
     * 故障分类
     */
    @RequestMapping("/troubleCatList")
    @ResponseBody
    public ResultDto troubleCatList() {
        return troubleCatBiz.troubleCatList();
    }

    @RequestMapping("/getOrdersByCode")
    @ResponseBody
    public ResultDto getOrdersByCode(String repairCode) {
        return repairOrderBiz.getOrdersByCode(repairCode);
    }


    /**
     * 上传接口
     */
    @RequestMapping("/qiNiuUpload")
    @ResponseBody
    public String upload(MultipartFile file) {
        String accesskey = Configuration.getConfigurationByName("qiniu.access.key");
        String ssecretKey = Configuration.getConfigurationByName("qiniu.secret.key");
        String bucketName = Configuration.getConfigurationByName("qiniu.bucket.name");
        String bucketHostName = Configuration.getConfigurationByName("qiniu.bucket.host.name");

        UploadUtil uploadUtil = UploadFactory.createUpload(accesskey, ssecretKey,
                bucketHostName, bucketName);
        return uploadUtil.uploadFile("/filePath/", file);
    }

    /**
     * 区域列表
     */
    @RequestMapping("/areaList")
    @ResponseBody
    public ResultDto areaList(String pageIndex, String pageSize, String searchParam) {
        return repairOrderBiz.areaList(pageIndex, pageSize, searchParam);
    }

    /**
     * 指派人员列表
     */
    @RequestMapping("/getUser")
    @ResponseBody
    public ResultDto getUser(String pageIndex, String pageSize, String userName, String userIds) {
        return repairOrderBiz.getUser(pageIndex, pageSize, userName, userIds);
    }


    /**
     * 指派岗位列表
     */
    @RequestMapping("/getPosition")
    @ResponseBody
    public ResultDto getPosition(String pageIndex, String pageSize, String positionIds) {
        return repairOrderBiz.getPosition(pageIndex, pageSize, positionIds);
    }


    /**
     * 保存指定人
     */
    @RequestMapping("/saveAssignList")
    @ResponseBody
    public ResultDto saveAssignList(String assignIds, String repairOrderId) {
        return repairOrderBiz.assignUsers(assignIds, repairOrderId);
    }

    /**
     * 保存指定岗位
     */
    @RequestMapping("/saveAssignPositionList")
    @ResponseBody
    public ResultDto saveAssignPositionList(String assignPositionIds, String repairOrderId) {
        return repairOrderBiz.assignPositions(assignPositionIds, repairOrderId);
    }

    /**
     * 巡检维修到场
     */
    @RequestMapping("/inspectionPresence")
    @ResponseBody
    public ResultDto inspectionPresence(String presencePhotos, String repairOrderId, String longitude, String latitude) {
        return repairOrderBiz.inspectionPresence(presencePhotos, repairOrderId, longitude, latitude);
    }


    /**
     * 参与人详情
     */
    @RequestMapping("/partnerDetail")
    @ResponseBody
    public ResultDto partnerDetail(String repairOrderId, String userId) {
        return repairOrderBiz.partnerDetail(repairOrderId, userId);
    }

    /**
     * 维修确认
     */
    @RequestMapping("/confirmRepair")
    @ResponseBody
    public ResultDto confirmRepair(String repairOrderId) {
        return repairOrderBiz.confirmRepair(repairOrderId);
    }

    /**
     * 签字确认
     */
    @RequestMapping("/saveSignPic")
    @ResponseBody
    public ResultDto saveSignPic(MultipartFile file, String repairOrderId) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise == null) {
            return ResultUtil.error("登陆过期");
        }
        return repairOrderBiz.saveSignPic(file, repairOrderId, enterprise);
    }


    /**
     * 维修复合查询条件
     *
     * @param catParentId
     * @param areaParentId
     * @return
     */
    @RequestMapping("/complexSearch")
    @ResponseBody
    public ResultDto complexSearch(String catParentId, String areaParentId) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise == null) {
            return ResultUtil.error("登陆过期");
        }
        //1区域，2专业，3报修等级，4维修单类型
        JSONObject result = new JSONObject();
        //专业
        JSONArray catArray = facilityCatBiz.findTreeData(StringConverters.ToLong(catParentId), enterprise != null ? enterprise.getId() : null);
        //区域
        JSONArray areaArray = areaBiz.findTreeData(StringConverters.ToLong(areaParentId), enterprise != null ? enterprise.getId() : null);
        //报修等级
        QueryParam queryParam = new QueryParam(-1, -1);
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        JSONArray repairLevelArray = repairLevelBiz.findJSONList(queryParam).getJSONArray("list");
        //维修单类型
        QueryParam queryParam1 = new QueryParam(-1, -1);
        queryParam1.getSqlMap().put("typeCode", "REPAIR_TYPE");
        queryParam1.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        JSONArray typeArray = dictInfoBiz.findJSONList(queryParam1).getJSONArray("list");

        result.put("catArray", catArray);
        result.put("areaArray", areaArray);
        result.put("repairLevelArray", repairLevelArray);
        result.put("typeArray", typeArray);
        return ResultUtil.success(result);
    }

}
